<template>
  <div style="width: 60%; margin: 10px auto">

    <div style="margin-bottom: 20px">
      <el-radio-group v-model="data.searchType">
        <el-radio label="宠物列表（文本搜索）" value="pageQuery">
          宠物列表（文本搜索）
        </el-radio>
        <el-radio label="宠物列表（图像搜索）" value="imageQuery">
          宠物列表（图像搜索）
        </el-radio>
      </el-radio-group>
    </div>

    <div v-if="data.searchType === 'pageQuery'">
      <div style="margin-bottom: 20px">
        <el-select v-model="data.typeId" placeholder="请选择宠物分类" size="large"
                   style="width: 200px; margin-right: 10px">
          <el-option v-for="type in data.typeList" :key="type.id" :label="type.name" :value="type.id"></el-option>
        </el-select>
        <el-input v-model="data.name" size="large" style="width: 500px; margin-right: 10px"
                  placeholder="请输入宠物名称"></el-input>
        <el-button size="large" type="primary" @click="load">搜索</el-button>
        <el-button size="large" type="info" @click="reset">重置</el-button>
      </div>

      <div style="margin: 20px 0" v-if="data.total > 0">
        <el-row :gutter="20">
          <el-col :span="6" v-for="pet in data.tableData" :key="pet.id">
            <div @click="router.push('/front/petDetail?id=' + pet.id)" class="card" style="padding: 0; margin-bottom: 20px;
                cursor: pointer; border-radius: 5px; overflow: hidden">
              <img :src="pet.image" alt="" style="width: 100%; height: 220px; display: block">
              <div style="padding: 10px">
                <div style="font-size: 20px; font-weight: bold; margin-bottom: 10px" class="line1">
                  <span>{{ pet.name }}</span>
                  <span style="font-size: 20px; color: red; margin-left: 20px; padding-right: 0">￥{{ pet.price }}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div style="padding: 20px; text-align: center; color: red" v-else>暂无搜索结果...</div>

      <div style="margin-top: 20px" v-if="data.total > 0">
        <el-pagination
            @current-change="load"
            @size-change="handleSizeChange"
            background layout="total, prev, pager, next, jumper, sizes"
            :page-sizes="[1, 3, 5, 10, 15, 20, 30]"
            :page-size="data.pageSize"
            v-model:current-page="data.pageNum"
            :total="data.total"/>
      </div>
    </div>

    <div v-if="data.searchType === 'imageQuery'">
      <!-- 第一部分：上传控件 -->
      <div class="section-container" style="padding: 20px; margin-bottom: 20px">
        <div style="display: flex; align-items: center; gap: 20px">
          <el-button size="large" type="primary" @click="triggerImageSearch" style="border-radius: 4px">{{ previewImage ? '更换图片' : '点击上传' }}</el-button>
          <el-button size="large" @click="handleImageSearch" style="border-radius: 4px">搜索</el-button>
          <el-button size="large" @click="resetImageSearch" style="border-radius: 4px">重置</el-button>
          <input ref="fileInput" type="file" accept="image/*" style="display: none" @change="handleImageSelect">
        </div>
      </div>

      <!-- 第二部分：图片预览 -->
      <div class="section-container" style="min-height: 200px; padding: 20px; margin-bottom: 20px">
        <div v-if="previewImage" style="text-align: center">
          <div style="font-size: 16px; color: #666; margin-bottom: 10px">上传的图片</div>
          <img :src="previewImage" style="max-width: 400px; border: 1px solid #ddd; padding: 4px; border-radius: 4px">
        </div>
        <div v-else style="text-align: center; color: #999; padding: 40px 0">
          <i class="el-icon-picture" style="font-size: 60px; display: block; margin-bottom: 10px"></i>
          <span>请先上传宠物图片</span>
        </div>
      </div>

      <div style="margin: 20px 0" v-if="imageData.total > 0">
        <el-row :gutter="20">
          <el-col :span="6" v-for="pet in imageData.tableData" :key="pet.id">
            <div @click="router.push('/front/petDetail?id=' + pet.id)" class="card" style="padding: 0; margin-bottom: 20px;
                cursor: pointer; border-radius: 5px; overflow: hidden">
              <img :src="pet.image" alt="" style="width: 100%; height: 220px; display: block">
              <div style="padding: 10px">
                <div style="font-size: 20px; font-weight: bold; margin-bottom: 10px" class="line1">
                  <span>{{ pet.name }}</span>
                  <span style="font-size: 20px; color: red; margin-left: 20px; padding-right: 0">￥{{ pet.price }}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div style="padding: 20px; text-align: center; color: red" v-else>暂无搜索结果...</div>

      <div style="margin-top: 20px" v-if="imageData.total > 0">
        <el-pagination
            @current-change="handleImageSearch"
            @size-change="handleImageSizeChange"
            background layout="total, prev, pager, next, jumper, sizes"
            :page-sizes="[1, 3, 5, 10, 15, 20, 30]"
            :page-size="imageData.pageSize"
            v-model:current-page="imageData.pageNum"
            :total="imageData.total"/>
      </div>
    </div>

  </div>
</template>

<script setup>
  import { reactive, ref } from "vue";
  import request from "@/utils/request.js";
  import router from "@/router/index.js";
  import {ElMessage} from "element-plus";

  const data = reactive({
    user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
    id: router.currentRoute.value.query.id,
    typeList: [],
    pageNum: 1,
    pageSize: 10,
    typeId: null,
    name: null,
    tableData: [],
    total: null,
    searchType: 'pageQuery'
  })

  request.get("/petType/query/all").then(res => {
    if (res.code === '200') {
      data.typeList = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })

  const load = () => {
    request.get('/pet/pageQuery', {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        typeId: data.typeId,
        name: data.name,
        status: '上架'
      }
    }).then(res => {
      if (res.code === '200') {
        data.tableData = res.data?.list
        data.total = res.data?.total
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
  load()

  const reset =  () => {
    data.typeId = null
    data.name = null
    load()
  }

  const handleSizeChange = (newSize) => {
    data.pageSize = newSize
    data.pageNum = 1
    load()
  }

  // *******************图像搜索*********************

  const imageData = reactive({
    pageNum: 1,
    pageSize: 10,
    image: null,
    tableData: [],
    total: null,
  })

  const fileInput = ref()
  const previewImage = ref()

  // 触发文件选择
  const triggerImageSearch = () => {
    // 清除历史选择
    fileInput.value.value = ''
    fileInput.value.click()
  }

  // 图片选择处理
  const handleImageSelect = (event) => {
    const file = event.target.files[0]
    if (!file) return

    if (!validateImageFile(file)) return

    // 存储文件对象和预览URL
    imageData.image = file
    previewImage.value = URL.createObjectURL(file)
  }

  // 文件验证方法
  const validateImageFile = (file) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/bmp']
    const maxSizeMB = 5

    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('仅支持 JPG/PNG/BMP 格式图片')
      return false
    }

    if (file.size > maxSizeMB * 1024 * 1024) {
      ElMessage.error(`图片大小不能超过 ${maxSizeMB}MB`)
      return false
    }

    return true
  }

  const handleImageSearch = () => {
    const formData = new FormData()
    formData.append('pageNum', imageData.pageNum)
    formData.append('pageSize', imageData.pageSize)
    formData.append('image', imageData.image)

    request.post('/recognize/search', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(res => {
      if (res.code === '200') {
        if(imageData.image) {
          ElMessage.success('图像搜索成功')
        }
        imageData.tableData = res.data?.list || []
        imageData.total = res.data?.total || 0
      } else {
        ElMessage.error(res.msg)
      }
    })
  }
  handleImageSearch()

  const resetImageSearch = () => {
    previewImage.value = null
    fileInput.value.value = ''
    imageData.image = null
    handleImageSearch()
  }


  const handleImageSizeChange = (newSize) => {
    imageData.pageSize = newSize
    imageData.pageNum = 1
    handleImageSearch()
  }

</script>

<style scoped>
.section-container {
  border: 1px solid #000;
  border-radius: 4px;
  margin-bottom: 20px;
  background: #fff;
}

/* 卡片悬停效果 */
.card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  transition: all 0.3s;
}
</style>